package services.application;

import com.avaje.ebean.Ebean;
import dto.app.AppInstallDto;
import models.application.*;
import models.pubobj.AniObjectState;
import models.user.*;
import services.AniPublicPropService;
import services.exception.AniDataException;
import services.exception.AniRuleException;

import java.util.*;

/**
 * User: yeh
 * Date: 2/3/13
 * Time: 10:55 AM
 * For:  wilddragon
 */
public class AniAppInstallService extends AniAppService {
    public static Boolean isAllAppInstalled(List<AniApp> apps, AniUser oneUser){
        if(apps == null || apps.isEmpty()){
            throw new AniRuleException("APPS_CANNOT_BE_EMPTY");
        }
        return AniUserAppRel.getInstalledAppCount(apps, oneUser) == apps.size();
    }

    public static void installOrRemoveApps(String appIds, AniUser oneUser){
        List<AppInstallDto> apps = AppInstallDto.generateAppIdListFromStr(appIds);
        if(apps == null && apps.size() < 1){
            throw new AniDataException("PARAM_DATA_ILLEGAL");
        }
        AniAppService.checkAppsExistenceWithIds(AppInstallDto.getIdList(apps));
        AniAppService.checkAppsPrivacyWithIds(
                AppInstallDto.getIdList(apps),
                AniPublicPropService.getObjectStateWithIdOrName(AniObjectState.States.ACTIVATED.name()));
        processInstallOrRemoveApps(apps, oneUser);
    }
    private static void processInstallOrRemoveApps(List<AppInstallDto> operationApps, AniUser oneUser){
        List<AniApp> appsDao = AppInstallDto.getAppsDao(operationApps);
        Map<Long, AniUserAppRel> installedApps = AniUserAppRel.getInstalledAppsUserRelMap(appsDao, oneUser);

        List<AniUserAppRel> modifiedApps = new ArrayList<AniUserAppRel>();
        AniObjectState activatedState = AniObjectState.findByStateKey(AniObjectState.States.ACTIVATED.name());
        AniObjectState retiredState = AniObjectState.findByStateKey(AniObjectState.States.RETIRED.name());
        for(AniApp oneApp: appsDao){
            AniUserAppRel oneUserAppRel = installedApps.get(oneApp.id);
            if(oneUserAppRel == null){
                modifiedApps.add(
                        new AniUserAppRel(
                                oneUser,
                                oneApp,
                                activatedState
                        )
                );
            }else{
                oneUserAppRel.state = retiredState;
                modifiedApps.add(oneUserAppRel);
            }
        }
        Ebean.save(modifiedApps);
    }

}
